import React, {useEffect, useState} from "react";
import {Button, Card, Carousel, Col, Divider, Input, Layout, Row, Typography} from "antd";
import Navbar from "../components/Navbar";
import "./css/HomePage.css";
import {BulbTwoTone, CloseOutlined, FireTwoTone, MessageFilled, NotificationTwoTone} from "@ant-design/icons";
import Reservation from "./Reservation";
import ReviewList from "../components/ReviewList";
import OrderPage from "./OrderPage";
import {useSelector} from "react-redux";
import axios from "axios";

const {Header, Footer, Content} = Layout;
const {Title, Text} = Typography;
const {TextArea} = Input;

const HomePage = () => {
    const [activePage, setActivePage] = useState("主页");
    const [currentDate, setCurrentDate] = useState("");
    const [chatVisible, setChatVisible] = useState(false);
    const [chatMessages, setChatMessages] = useState([]);
    const [chatInput, setChatInput] = useState("");
    const user = useSelector((state) => state.user.user);

    useEffect(() => {
        const date = new Date().toLocaleDateString();
        setCurrentDate(date);
        // 每5秒请求一次最新信息
        const intervalId = setInterval(() => {
            axios.get('http://localhost:5532/notification/user?userId='+user.id).then(res => {
                if (res.data.code === 1){
                    var list = res.data.data;
                    if (list && list.length > 0){
                        list.forEach(item => {
                            setChatMessages(chatMessages => [...chatMessages, {sender: item.fromId, content: item.content}])
                        })
                    }
                }
            })
        }, 5000);
    }, []);

    const handleSendMessage = () => {
        if (!chatInput.trim()) return;
        const newMessage = {sender: user.id, content: chatInput};
        setChatMessages([...chatMessages, newMessage]);
        setChatInput("");
        axios.post('http://localhost:5532/notification/send', {
            fromId: user.id,
            toId: 0,
            content: chatInput,
        }).catch(error => console.error('Chat API error:', error));
    };


    return (
        <Layout className="homepage-layout">
            <Header className="homepage-header">
                <Navbar setActiveComponent={setActivePage}/>
            </Header>
            {activePage === "预约项目" && (
                <Layout>
                    <Reservation/>
                </Layout>

            )}
            {activePage === "我的订单" && (
                <Layout>
                    <OrderPage/>
                </Layout>
            )}
            {activePage === "主页" && (
                <Layout>
                    <Content className="homepage-content">
                        <div className="homepage-main">
                            <Carousel autoplay arrows={true} speed={500} fade={true}>
                                <div>
                                    <Card className="module-card welcome-card" bordered={false}>
                                        <Title level={2} className="welcome-title">
                                            欢迎来到诚栋医美预约系统
                                        </Title>
                                        <Text className="date-text">今天是 {currentDate}</Text>
                                        <br/><Text className="date-text">祝您心情愉快</Text>
                                    </Card>
                                </div>
                                <div>
                                    <img src={process.env.PUBLIC_URL + '/img/zhanshitu1.png'} alt="err"
                                         style={{height: '300px'}}/>
                                </div>
                                <div>
                                    <img src={process.env.PUBLIC_URL + '/img/zhanshitu2.png'} alt="err"
                                         style={{height: '300px'}}/>
                                </div>
                                <div>
                                    <img src={process.env.PUBLIC_URL + '/img/zhanshitu3.png'} alt="err"
                                         style={{height: '300px'}}/>
                                </div>
                            </Carousel>
                            <Divider/>
                            <Row gutter={[16, 16]}>
                                <Col xs={24} sm={12} md={8}>
                                    <Card
                                        hoverable={true}
                                        title="我们是谁"
                                        className="module-card action-card"
                                        bordered={false}
                                        extra={(<BulbTwoTone/>)}
                                    >
                                        <ul className="service-list">
                                            <li>我们是全中国最有实力的医美企业</li>
                                            <li>我们短短10年就成为行业领军人物</li>
                                            <li>我们脱胎于一个大学生的毕设项目</li>
                                        </ul>
                                    </Card>
                                </Col>
                                <Col xs={24} sm={12} md={8}>
                                    <Card
                                        hoverable={true}
                                        title="快速预约"
                                        className="module-card action-card"
                                        bordered={false}
                                        extra={(<FireTwoTone/>)}
                                    >
                                        <Button
                                            type="primary"
                                            block
                                            onClick={() => setActivePage("预约项目")}
                                        >
                                            立即预约
                                        </Button>
                                    </Card>
                                </Col>

                                <Col xs={24} sm={12} md={8}>
                                    <Card
                                        hoverable={true}
                                        title="商家公告"
                                        className="module-card action-card"
                                        bordered={false}
                                        extra={(<NotificationTwoTone/>)}
                                    >
                                        <Text strong>本月新用户享受8折优惠！</Text>
                                    </Card>
                                </Col>
                            </Row>
                            <Divider/>
                            <ReviewList/>
                        </div>
                    </Content>
                </Layout>
            )}
            <Footer className="homepage-footer">
                © 2025 武诚栋的美容院预约系统
            </Footer>
            <div className={`chat-sidebar ${chatVisible ? "visible" : "hidden"}`}>
                <div className="chat-header">
                    <Title level={4}>在线客服</Title>
                    <Button
                        icon={<CloseOutlined/>}
                        type="link"
                        onClick={() => setChatVisible(false)}
                    ></Button>
                </div>
                <div className="chat-messages">
                    {chatMessages.map((msg, index) => (
                        <div key={index} className={`chat-message ${msg.sender === 0 ? 'bot' : 'user'}`}>
                            <span>{msg.content}</span>
                        </div>
                    ))}
                </div>
                <div className="chat-input-container">
                    <TextArea
                        rows={3}
                        value={chatInput}
                        onChange={(e) => setChatInput(e.target.value)}
                        placeholder="请输入您的问题..."
                    />
                    <Button
                        type="primary"
                        onClick={handleSendMessage}
                        style={{marginTop: "10px"}}
                        block
                    >
                        发送
                    </Button>
                </div>
            </div>
            <Button
                icon={<MessageFilled style={{fontSize: "24px"}}/>}
                className="toggle-chat-btn"
                type="text"
                onClick={() => setChatVisible(!chatVisible)}
            ></Button>
        </Layout>
    );
};

export default HomePage;
